__all__ = ['Items']
from ..storage import *
class Items(Storage):

    SQL_DROP = ["""
        DROP TABLE IF EXISTS "items"
    """]

    SQL_CREATE = ["""
        CREATE TABLE "items" (
            "item_id"               integer     not null,
            "group_id"              integer         null,
            "graphic"               integer         null,
            "volume"                real        not null,
            "mass"                  real        not null,
            "name"                  text        not null,
            PRIMARY KEY ("item_id")
        ) WITHOUT OIDS """,
        """ CREATE INDEX "items_volume" ON "items" ("volume") """,
        """ CREATE INDEX "items_mass"   ON "items" ("mass"  ) """,
    ]

    SQL_INSERT = ["""
        INSERT INTO "items" (
            "item_id",
            "group_id",
            "graphic",
            "volume",
            "mass",
            "name"
        ) VALUES (
            %(item_id)s,
            %(group_id)s,
            %(graphic)s,
            %(volume)s,
            %(mass)s,
            %(name)s
        )
    """]

    SQL_ANALYZE = ["""
        ANALYZE "items"
    """]

    def drop(self):
        self.execute(self.SQL_DROP)

    def create(self):
        self.execute(self.SQL_CREATE)

    def insert(self, rows):
        self.execute(self.SQL_INSERT, rows)

    def analyze(self):
        self.execute(self.SQL_ANALYZE)

    def adapt(self, fetcher):
        return\
            map(lambda row: {
                'item_id'           : row['typeID'          ],
                'group_id'          : row['marketGroupID'   ],
                'graphic'           : row['graphicID'       ],
                'volume'            : row['volume'          ],
                'mass'              : row['mass'            ],
                'name'              : row['typeName'        ],
            },
            filter(lambda row: row['typeName'] != '',
            fetcher({
                'typeID'            : int,
                'marketGroupID'     : int,
                'graphicID'         : int,
                'volume'            : float,
                'mass'              : float,
                'typeName'          : str,
            }, 'invTypes')))
